package com.briup.common.utils;

import com.briup.common.exception.ServiceException;
import com.briup.common.response.ResultCode;
import org.springframework.util.StringUtils;

import java.util.function.Consumer;

/**
 * 断言工具类，用于在代码中进行断言判断，若断言失败则抛出异常
 */
public class AssertUtil {

    /**
     * 断言判断，若对象为null则抛出异常
     *
     * @param obj     待判断对象
     * @param message 异常消息
     */
    public static void notNull(Object obj, String message) {
        if (obj == null) {
            throw new ServiceException(message);
        }
    }

    /**
     * 断言判断，若对象为null则抛出异常
     *
     * @param obj        待判断对象
     * @param resultCode 响应枚举
     */
    public static void notNull(Object obj, ResultCode resultCode) {
        if (obj == null) {
            throw new ServiceException(resultCode);
        }
    }

    /**
     * 断言判断，若对象不为null则抛出异常
     *
     * @param obj     待判断对象
     * @param message 异常消息
     */
    public static void requiredNull(Object obj, String message) {
        if (obj != null) {
            throw new ServiceException(message);
        }
    }

    /**
     * 断言判断，若对象不为null则抛出异常
     *
     * @param obj        待判断对象
     * @param resultCode 响应枚举
     */
    public static void requiredNull(Object obj, ResultCode resultCode) {
        if (obj != null) {
            throw new ServiceException(resultCode);
        }
    }

    /**
     * 断言判断，若条件为false则抛出异常
     *
     * @param condition 断言条件
     * @param message   异常消息
     */
    public static void isTrue(boolean condition, String message) {
        if (!condition) {
            throw new ServiceException(message);
        }
    }

    /**
     * 断言判断，若条件为false则抛出异常
     *
     * @param condition  断言条件
     * @param resultCode 响应枚举
     */
    public static void isTrue(boolean condition, ResultCode resultCode) {
        if (!condition) {
            throw new ServiceException(resultCode);
        }
    }

    /**
     * 断言判断，若字符串为空则抛出异常，包含空字符串和只包含空格的字符串
     *
     * @param str     待判断字符串
     * @param message 异常消息
     */
    public static void hasText(String str, String message) {
        if (!StringUtils.hasText(str)) {
            throw new ServiceException(message);
        }
    }

    /**
     * 断言判断，若字符串为空则抛出异常，包含空字符串和只包含空格的字符串
     *
     * @param str        待判断字符串
     * @param resultCode 响应枚举
     */
    public static void hasText(String str, ResultCode resultCode) {
        if (!StringUtils.hasText(str)) {
            throw new ServiceException(resultCode);
        }
    }

    public static Consumer<Class<? extends Exception>> check(boolean condition, String message) {
        return exceptionClass -> {
            if (!condition) {
                try {
                    throw exceptionClass.getDeclaredConstructor(String.class)
                            .newInstance(message);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }
}
